import { type Ref, ref, reactive, toRaw, onMounted, h } from "vue";
import editForm from "../form.vue";
import { usePublicHooks } from "@/views/hooks";
import { ElMessageBox } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import { getFullUrl } from "@/utils/auth";
import JSONEditor from "json-editor-vue";
import {
  type ParkingLot,
  getParkingPage,
  addParking,
  editParking,
  deleteParking,
  sendConfig
} from "@/api/parking";
import normalAvatar from "@/assets/normal-img.png";
import { ElForm, ElInput, ElFormItem } from "element-plus";
import {
  getKeyList,
  cloneDeep,
  isAllEmpty,
  deviceDetection
} from "@pureadmin/utils";
import {
  IconifyIconOffline,
  IconifyIconOnline,
  FontIcon
} from "@/components/ReIcon";
import Site from "~icons/ri/map-pin-fill";
const { parkadeTypeStyle, parkadeChargeTypeStyle, enableStyle } =
  usePublicHooks();
import dayjs from "dayjs";
export function useDict(tableRef: Ref) {
  const { switchStyle } = usePublicHooks();
  const form = reactive({
    queryStartTime: "",
    queryEndTime: dayjs().format("YYYY-MM-DD 23:59:59"),
    pageNum: 1,
    pageSize: 10,
    orderByColumn: "",
    isAsc: "asc",
    name: "",
    isEnabled: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(false);
  const selectedNum = ref(0);
  const switchLoadMap = ref({});
  // 分页配置
  const pagination = reactive({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 表格列配置
  const columns: TableColumnList = [
    {
      label: "停车场",
      prop: "coverImageUrl",
      minWidth: 180,
      align: "left",
      cellRenderer: ({ row }) => (
        <div class="flex">
          <div class="mr-2">
            <el-image
              fit="cover"
              preview-teleported={true}
              src={
                row.coverImageUrl ? getFullUrl(row.coverImageUrl) : normalAvatar
              }
              preview-src-list={Array.of(
                row.coverImageUrl ? getFullUrl(row.coverImageUrl) : normalAvatar
              )}
              style="width: 44px; height: 44px"
              class="rounded-[5px] align-middle"
            />
          </div>
          <div>
            <div class="mb-[2px] text-[14px]">{row.name}</div>
            <div class="text-[12px] flex items-center">
              <IconifyIconOffline class="site" icon={Site} size={16} />
              <span class="pl-0.5">{row.address}</span>
            </div>
          </div>
        </div>
      )
    },
    {
      label: "停车场类型",
      prop: "parkingType",
      minWidth: 100,
      width: "100px",
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={parkadeTypeStyle.value(row.parkingType).style}
        >
          {parkadeTypeStyle.value(row.parkingType).text}
        </el-tag>
      )
    },
    { label: "总车位", prop: "totalCapacity" },
    { label: "实时停车位", prop: "currentCapacity" },
    // {
    //   label: "收费规则",
    //   prop: "chargeRules",
    //   cellRenderer: ({ row }) =>
    //     row.chargeRules ? row.chargeRules || JSON.parse(row.chargeRules) : "-"
    // },
    // {
    //   label: "高德经纬度",
    //   prop: "gaodelot",
    //   minWidth: 120,
    //   width: "120px",
    //   cellRenderer: ({ row }) => row.gaodelot + row.gaodelat
    // },
    {
      label: "是否在线",
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={row.isOnline ? "success" : "danger"}>
          {row.isOnline ? "在线" : "离线"}
        </el-tag>
      )
    },
    // {
    //   label: "停车场经纬度",
    //   prop: "longitude",
    //   minWidth: 120,
    //   width: "120px",
    //   cellRenderer: ({ row }) => row.longitude + row.latitude
    // },
    {
      label: "经纬度",
      prop: "longitude",
      minWidth: 140,
      cellRenderer: ({ row }) => (
        <span>{(row.longitude || "") + "-" + (row.latitude || "")}</span>
      )
    },
    {
      label: "描述",
      prop: "description",
      cellRenderer: ({ row }) => (row.description ? row.description : "-")
    },
    {
      label: "收费类型",
      prop: "chargeType",
      minWidth: 100,
      width: "100px",
      cellRenderer: ({ row }) =>
        parkadeChargeTypeStyle.value(row.chargeType).text || "-"
    },
    { label: "排序", prop: "sortCode" },
    // { label: "创建时间", prop: "CreateDate" },
    // { label: "创建人", prop: "CreateUserName" },
    {
      label: "是否启用",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.isEnabled}
          active-text="启用"
          inactive-text="停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    // { label: "备注", prop: "Description" },
    {
      label: "操作",
      fixed: "right",
      width: "240px",
      slot: "operation" // 包含编辑、删除等操作
    }
  ];
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    pagination.pageSize = val;
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    pagination.currentPage = val;
    form.pageNum = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    console.log(`handleSelectionChange: ${val}`);
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }
  /** 批量删除 */
  function onBatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    if (!curSelected.length) {
      message("请选择要删除的记录", { type: "warning" });
      return;
    }
    const Ids = curSelected.map(item => item.id);
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    deleteDictTypeBatch(Ids).then(() => {
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    });
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
  }
  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.isEnabled ? "启用" : "停用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        // 编辑
        await editParking(row);
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: false
          }
        );
        message("已成功修改", {
          type: "success"
        });
        await onSearch();
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
        onSearch();
      });
  }
  // 获取停车场列表
  async function onSearch() {
    loading.value = true;
    const { data } = await getParkingPage(toRaw(form));
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.size;
    pagination.currentPage = data.current;
    setTimeout(() => (loading.value = false), 500);
  }
  // 新增/编辑停车场
  function openDialog(type: string, row?: ParkingLot) {
    const title = type === "add" ? "新增" : "编辑";
    addDialog({
      title: `${title}停车场`,
      props: {
        formInline: {
          id: row?.id || "",
          name: row?.name || "",
          parkingType: row?.parkingType || null,
          totalCapacity: row?.totalCapacity || null,
          chargeRules: row?.chargeRules || "",
          chargeType: row?.chargeType || null,
          longitude: row?.longitude || "",
          latitude: row?.latitude || "",
          // gaodelot: row?.gaodelot || "",
          // gaodelat: row?.gaodelat || "",
          address: row?.address || "",
          coverImageUrl: row?.coverImageUrl || "",
          sortCode: row?.sortCode || 99,
          // isDeleted: row?.isDeleted || "",
          isEnabled: row?.isEnabled || null,
          description: row?.description || ""
          // createdAt: row?.createdAt || ""
        }
      },
      width: "720px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as ParkingLot;
        curData.chargeRules = JSON.stringify(curData.chargeRules);
        async function chores() {
          message(`您${title}了停车场名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          await onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (type === "add") {
              delete curData.id;
              await addParking(curData);
              await chores();
            } else {
              // 编辑
              curData.id = row.id;
              await editParking(curData);
              await chores();
            }
          }
        });
      }
    });
  }
  // 配置
  const configForm = reactive({
    config: ""
  });
  const ruleFormRef = ref();
  function sendToConfig(row) {
    configForm.config = row.config ?? "";
    addDialog({
      title: "下发配置",
      width: "600px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <>
          <ElForm ref={ruleFormRef} model={configForm}>
            <ElFormItem
              style={{ with: "580px" }}
              prop="config"
              rules={[
                {
                  required: true,
                  message: "请输入配置",
                  trigger: "blur"
                },
                {
                  validator: (rule, value, callback) => {
                    try {
                      JSON.parse(value);
                      callback();
                    } catch (e) {
                      callback(new Error("无效的JSON格式：" + e.message));
                    }
                  },
                  trigger: "blur"
                }
              ]}
            >
              <JSONEditor
                v-model={configForm.config}
                mode="code"
                mainMenuBar={true}
                statusBar={true}
                formatOnSave={true}
                autoFormat={true}
                style={{ height: "400px", with: "580px" }}
                onError={err => {
                  message("JSON格式错误：" + err.message, {
                    type: "error"
                  });
                }}
              />
            </ElFormItem>
            <div class="flex" style="display:none;">
              <div
                class="mr-2 cursor-pointer"
                onClick={() => {
                  try {
                    const parsed = JSON.parse(configForm.config);
                    configForm.config = JSON.stringify(parsed, null, 2);
                  } catch (e) {
                    message("JSON格式错误：" + e.message, {
                      type: "error"
                    });
                  }
                }}
              >
                格式化JSON
              </div>
              <div
                class="cursor-pointer"
                onClick={async () => {
                  try {
                    await navigator.clipboard.writeText(configForm.config);
                    message("复制成功", {
                      type: "success"
                    });
                  } catch (err) {
                    message("复制失败：" + err.message, {
                      type: "error"
                    });
                  }
                }}
              >
                复制
              </div>
            </div>
          </ElForm>
        </>
      ),
      beforeSure: (done, { options }) => {
        const tempCofig =
          typeof configForm.config == "string"
            ? configForm.config
            : JSON.stringify(configForm.config);
        const curData = {
          ...row,
          config: tempCofig ?? ""
        };
        async function chores() {
          done(); // 关闭弹框
          await onSearch(); // 刷新表格数据
        }
        ruleFormRef.value.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            await editParking(curData);
            // 表单规则校验通过
            await sendConfig({ clientId: row.id })
              .then(() => {
                tableRef.value.getTableRef().clearSelection();
                message(`发送成功！`, {
                  type: "success"
                });
                onSearch();
              })
              .catch(() => {
                message(`发送失败！`, {
                  type: "warning"
                });
              });
            await chores();
          }
        });
      }
    });
  }
  // 删除停车场
  function handleDelete(row) {
    // ElMessageBox.confirm(`确认删除停车场【${row.name}】?`, "删除确认", {
    //   type: "warning"
    // }).then(() => {
    deleteParking(row.id).then(() => {
      message(`删除停车场 ${row.name} 成功`, { type: "success" });
      // 重置分页到第一页
      pagination.currentPage = 1;
      onSearch();
    });
    // });
  }

  onMounted(async () => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onBatchDel,
    onSearch,
    resetForm,
    openDialog,
    sendToConfig,
    handleDelete,
    onSelectionCancel,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
